package com.example.prison.util;

import com.example.prison.service.SystemInfoService;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 服务端主类 UDPServer
 *
 * @author PP Lu
 */
public class TCPServer {

    private final Logger logger = LoggerFactory.getLogger(TCPServer.class);

    SystemInfoService systemInfoService = (SystemInfoService) SpringUtil.getBean("systemInfoServiceImpl");

    public void run() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(10);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap
                    .group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
//                            pipeline.addLast(new JsonObjectDecoder());
                            pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
                            pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
                            pipeline.addLast(new TCPServerHandler());
                        }
                    }); //自定义一个初始化类

//            System.out.println("***端口" + port + "绑定成功！***");
//            logger.info("***端口" + port + "绑定成功！***");
            String ip = systemInfoService.get().get(0).getGatewayAddress();
            int port = Integer.parseInt(systemInfoService.get().get(0).getGatewayPort());

//            ChannelFuture channelFuture = serverBootstrap.bind("10.10.10.110",8886).sync();
            ChannelFuture channelFuture = serverBootstrap.bind(ip,port).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
//            System.out.println("***端口" + port + "解除绑定！***");
//            logger.info("***端口" + port + "解除绑定！***");
        }
    }

}
